<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2021/01/22
 * Time: 17:49
 */
namespace App\Api\Controllers\YinSheng;


use App\Api\Controllers\Config\WftPayConfigController;
use App\Api\Controllers\Config\YinshengConfigController;
use EasyWeChat\Factory;
use Illuminate\Http\Request;

class OauthOpenidController extends \App\Api\Controllers\DevicePay\BaseController
{

    //授权签名openID
    public function oauth_sign_openid(Request $request)
    {
        $data = $request->all(); //第三方传过来的信息

        $check = $this->check_md5($data); //验证签名
        if ($check['return_code'] == 'FALL') {
            return $this->return_data($check);
        }

        $config_id = $data['config_id'];
        $callback_url = $data['callback_url'];

        $config = new YinshengConfigController();
        $yinsheng_config = $config->yinsheng_config($config_id);
        if (!$yinsheng_config) {
            return json_encode([
                'status' => 2,
                'message' => '银盛支付配置不存在请检查配置'
            ]);
        }
        $config = [
            'app_id' => $yinsheng_config->wx_appid,
            'scope' => 'snsapi_base',
            'oauth' => [
                'scopes' => ['snsapi_base'],
                'response_type' => 'code',
                'callback' => url('api/yinsheng/weixin/oauth_sign_callback_openid?wx_AppId=' . $yinsheng_config->wx_appid . '&wx_Secret=' . $yinsheng_config->wx_secret . '&callback_url=' . $callback_url),
            ],
        ];
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;

        return $oauth->redirect();
    }


    //
    public function oauth_sign_callback_openid(Request $request)
    {
        $callback_url = $request->get('callback_url');
        $code = $request->get('code');
        $wx_AppId = $request->get('wx_AppId');
        $wx_Secret = $request->get('wx_Secret');
        $config = [
            'app_id' => $wx_AppId,
            "secret" => $wx_Secret,
            "code" => $code,
            "grant_type" => "authorization_code",
        ];

        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;
        $user = $oauth->user();
        $open_id = $user->getId();

        return redirect($callback_url . '?open_id=' . $open_id);
    }


}
